package com.yonyou.hxjy.service.dingtalk.Impl.toysImpl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yonyou.hxjy.entity.ProcessInstance;
import com.yonyou.hxjy.enums.DingDingComponent;
import com.yonyou.hxjy.service.dingtalk.DingtalkAdvancePaymentToYs;
import com.yonyou.hxjy.service.dingtalk.DingtalkProcessInstanceToYs;
import com.yonyou.hxjy.service.dingtalk.Impl.YsDataGetService;
import com.yonyou.hxjy.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class DingtalkAdvancePaymentToYsImpl implements DingtalkAdvancePaymentToYs {

    @Autowired
    private YsDataGetService ysDataGetService;

    @Autowired
    private DingtalkProcessInstanceToYs defaultDataService;

    private static final Logger logger = LoggerFactory.getLogger(DingtalkAdvancePaymentToYs.class);

    /**
     * 保存预付款收款单到Ys中
     * @param jsonObjectList
     * @return
     */
    @Override
    public List<JSONObject> advancePayment_toYsJson(List<JSONObject> jsonObjectList) {
//        List<JSONObject> filterReviewer = defaultDataService.filter_Reviewer(jsonObjectList);
        List<JSONObject> ysJsonResponseList = new ArrayList<>(); //返回结果列表
        Map<String, Object> dataMap = null; //参数汇总
        //保存收付款类型
        String saveType = "";
        //保存付款对象标识
        String caobject;
        //获取单据号(显示错误信息)
        String businessId = "";
        //获取响应结果
        JSONObject jsonObjectResponse;
        //获取银行数据
        List<JSONObject> bankList = ysDataGetService.getBankDetailsMessage();
        //获取供应商列表
        List<JSONObject> vendorList = ysDataGetService.getVendorDetailsMessage();

        //遍历ID集合构建参数
        for (JSONObject jsonObject : jsonObjectList) {
            try {
                //保存付款对象标识
                caobject = "";
                //获取审批实例业务编号
                businessId = jsonObject.getJSONObject("result").getStr("businessId");
                JSONArray jsonArrayTasks = jsonObject.getJSONObject("result").getJSONArray("tasks");
                //审批id对象
                ProcessInstance processInstance = defaultDataService.getProcessInstance(jsonArrayTasks);
                Date dateTime = processInstance.getCreateDate();
                String processInstanceId =processInstance.getProcessInstanceId();
                dataMap = new HashMap<>();
                //构建主表参数
                Map <String,Object> paramMap = new HashMap<>();
                paramMap.put("vouchdate",dealTime(jsonObject.getJSONObject("result").getStr("createTime"))); //日期
                paramMap.put("exchangeRateType_code",defaultDataService.EXCHANGE_RATE_TYPE_CODE); //交易类型
                paramMap.put("description",businessId); //审批单据号
                paramMap.put("code",businessId); //审批单据号
                paramMap.put("exchRate",defaultDataService.EXCH_RAGE); //汇率
                paramMap.put("currency_code",defaultDataService.CURRENCY_CODE); //币种code
                paramMap.put("_status","Insert"); //动作

                //构建资金付款单子表参数
                List<Map<String, Object>> fundPaymentBList = new ArrayList<>();
                Map<String, Object> fundPaymentBItem = new HashMap<>();
                fundPaymentBItem.put("settlestatus", "1"); // 结算方式
                fundPaymentBItem.put("_status", "Insert"); // 动作


                //设置单据创建时间
                processInstance.setCreate(jsonObject.getJSONObject("result").getStr("create"));

                List<JSONObject> jsonArray = jsonObject.getJSONObject("result").getJSONArray("formComponentValues").toList(JSONObject.class);
                List<JSONObject> sqrList = jsonArray.stream()
                        .filter(json -> "InnerContactField_WER6P2TO37K0".equals(json.getStr("id")))
                        .collect(Collectors.toList());
                if(sqrList.size()>0){
                    JSONObject sqr = sqrList.get(0);
                    List<JSONObject> extValue = sqr.getJSONArray("extValue").toList(JSONObject.class);
                    if(extValue.size()>0){
                        fundPaymentBItem.put("operator_code", extValue.get(0).getStr("emplId")); // 动作
                    }
                }
                //遍历组件里的value值
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject item = jsonArray.get(i);
                    //设置金额
                    if ("MoneyField-JPATT8BR".equals(item.getStr("id"))){
                        double oriSum = Double.parseDouble(item.getStr("value"));
                        if (oriSum < 0){
                            saveType = "fundCollection";
                            paramMap.put("tradetype_code", defaultDataService.TRADE_TYPE_CODE[3]); //交易类型(其他付款)
                            fundPaymentBItem.put("oriSum", Math.abs(oriSum)); //转为正数
                        }else {
                            saveType = "fundPayment";
                            paramMap.put("tradetype_code", defaultDataService.TRADE_TYPE_CODE[1]); //交易类型(采购付款)
                            fundPaymentBItem.put("oriSum", oriSum);
                        }
                        continue;
                    }
                    //设置部门编码
                    if ("TableField-MINGXI".equals(item.getStr("id"))){
                        JSONArray value = item.getJSONArray("value");
                        JSONArray rowValue = value.getJSONObject(0).getJSONArray("rowValue");
                        //检查该数据中是否包含extendValue
                        if (rowValue.getJSONObject(0).containsKey("extendValue")){
                            JSONArray extendValue = rowValue.getJSONObject(0).getJSONArray("extendValue");
                            String dept_code = extendValue.getJSONObject(0).getStr("id");
                            paramMap.put("dept_code",dept_code);
                            //System.out.println("部门编码:"+dept_code);
                        }
                        continue;
                    }
                    //设置款项类型
                    if ("DDSelectField_1D8BICWKWD5S0".equals(item.getStr("id"))){
                        String type = item.getStr("value");
                        if ("预付款".equals(type)){
                            fundPaymentBItem.put("quickType_code", defaultDataService.QUICK_TYPE_CODE[1]); // 款项类型(预付款)
                            //根据款项类型设置付款对象
                            fundPaymentBItem.put("caobject", 2); // 付款对象(供应商)
                            caobject = "vendor"; //供应商

                        }else if(type.contains("收押金")){
                            fundPaymentBItem.put("quickType_code", defaultDataService.QUICK_TYPE_CODE[6]); //款项类型(押金)
                            //根据款项类型设置付款对象
                            fundPaymentBItem.put("caobject", 2); // 付款对象(供应商)
                            caobject = "vendor"; //供应商

                        }else if ("备用金".equals(type)){
                            fundPaymentBItem.put("quickType_code", defaultDataService.QUICK_TYPE_CODE[5]); //款项类型(备用金)
                            fundPaymentBItem.put("caobject", 4); // 收款对象(其他)
                            caobject = "other"; //其他

                        }else if("借款".equals(type)){
                            fundPaymentBItem.put("quickType_code", defaultDataService.QUICK_TYPE_CODE[4]); //款项类型(借款)
                            fundPaymentBItem.put("caobject", 4); // 收款对象(其他)

                        }else if(type.contains("付押金")){
                            fundPaymentBItem.put("quickType_code", defaultDataService.QUICK_TYPE_CODE[3]); //款项类型(借款)
                            fundPaymentBItem.put("caobject", 2); // 收款对象(供应商)
                            caobject = "vendor"; //供应商
                        }else {
                            throw new RuntimeException("{error:\"获取企业银行账号失败-预付款审批单"+businessId+"中款项类型不存在！！！\"}");
                        }
                        continue;
                    }
                    //设置主体(组织单元)
                    if ("DDSelectField_1B6NZ0TBQOW00".equals(item.getStr("id"))){
                        //付款主体为其他主体直接跳出本次循环
                        if ("其他主体".equals(item.getStr("value"))){
                            continue;
                        }
                        //缓存到redis中
                        String uitCodeKey = "组织名称:" + item.getStr("value");
                        String uitCode = (String) RedisUtils.get(uitCodeKey);
                        //不存在发送请求获取组织编码
                        if (StringUtils.isEmpty(uitCode)){
                            //根据组织名称获取code
                            uitCode = ysDataGetService.getOrgUitCode(item.getStr("value"));
                            RedisUtils.set(uitCodeKey, uitCode);
                        }
                        if (uitCode!=null && !uitCode.isEmpty()){
                            paramMap.put("accentityRaw_code",uitCode ); //会计主体code
                            paramMap.put("accentity_code", uitCode); //资金组织code
                            paramMap.put("org_code", uitCode); //业务组织code
                            String bankCode = defaultDataService.getBankCode(item.getStr("value"),bankList);
                            if (bankCode!=null && !bankCode.isEmpty()){
                                paramMap.put("enterprisebankaccount_code",bankCode);// 企业银行账户编码
                                fundPaymentBItem.put("enterprisebankaccount_code", bankCode); // (子表)企业银行账户编码
                            }else {
                                throw new RuntimeException("{error:\"获取企业银行账号失败-预付款审批单"+businessId+"中默认银行账号不存在！！！\"}");
                            }
                        }else {
                            throw new RuntimeException("{error:\"获取组织code失败-预付款审批单"+businessId+"中组织单元不存在！！！\"}");
                        }
                        continue;
                    }
                    //付款主体为其他主体
                    if("DDSelectField_4EFG20QMDPC0".equals(item.getStr("id"))){
                        if (item.containsKey("extValue")){
                            //缓存到redis中
                            String uitCodeKey = "组织名称:" + item.getStr("value");
                            String uitCode = (String) RedisUtils.get(uitCodeKey);
                            //不存在发送请求获取组织编码
                            if (StringUtils.isEmpty(uitCode)){
                                //根据组织名称获取code
                                uitCode = ysDataGetService.getOrgUitCode(item.getStr("value"));
                                RedisUtils.set(uitCodeKey, uitCode);
                            }
                            if (uitCode!=null && !uitCode.isEmpty()){
                                paramMap.put("accentityRaw_code",uitCode ); //会计主体code
                                paramMap.put("accentity_code", uitCode); //资金组织code
                                paramMap.put("org_code", uitCode); //业务组织code
                                String bankCode = defaultDataService.getBankCode(item.getStr("value"),bankList);
                                if (bankCode!=null && !bankCode.isEmpty()){
                                    paramMap.put("enterprisebankaccount_code",bankCode);// 企业银行账户编码
                                    fundPaymentBItem.put("enterprisebankaccount_code", bankCode); // (子表)企业银行账户编码
                                }else {
                                    throw new RuntimeException("{error:\"获取企业银行账号失败-预付款审批单"+businessId+"中默认银行账号不存在！！！\"}");
                                }
                            }else {
                                throw new RuntimeException("{error:\"获取组织code失败-预付款审批单"+businessId+"中组织单元不存在！！！\"}");
                            }
                            continue;
                        }
                    }
                    //设置收款人银行账号和结算方式
                    if ("RecipientAccountField-JVM0OK11".equals(item.getStr("id"))){
                        if (item.containsKey("extValue")){
                            JSONObject extValueJson = item.getJSONObject("extValue");
                            if("vendor".equals(caobject)) {
                                if (!extValueJson.containsKey("cardNo")) {
                                    logger.error("供应商银行账号不存在!");
                                    //throw new RuntimeException("{error:\"获取供应商银行账号失败-预付款审批单" + businessId + "中供应商收款账号不存在！！！\"}");
                                }
                            }
                            String identityType = extValueJson.getStr("identityType");
                            String name = extValueJson.getStr("name");
                            fundPaymentBItem.put("oppositeobjectname", name); // 付款单位
                            fundPaymentBItem.put("oppositeaccountname",name);//收款方账户名称。
                            //结算方式判断
                            if ("CORP_BANK_CARD".equals(identityType) || "PERSONAL_BANK_CARD".equals(identityType)){
                                if (!extValueJson.containsKey("cardNo")) {
                                    throw new RuntimeException("{error:\"获取供应商银行账号失败-预付款审批单" + businessId + "中供应商收款账号不存在！！！\"}");
                                }
                                paramMap.put("settlemode_code",defaultDataService.SETTLEMODE_CODE[0]); //结算方式
                                fundPaymentBItem.put("settlemode_code",defaultDataService.SETTLEMODE_CODE[0]); //子表结算方式
                                String cardNo = extValueJson.getStr("cardNo");
                                fundPaymentBItem.put("oppositeaccountno", cardNo); // 收款(付款)银行账号

                                //供应商子表银行网点信息参数
                                Map<String,Object> bankParamMap = new HashMap<>();
                                bankParamMap.put("account",extValueJson.getStr("cardNo")); //银行账号
                                bankParamMap.put("accountname",extValueJson.getStr("name")); ////账号名称
                                //获取银行网点信息
                                String instBranchName1 = extValueJson.getStr("instBranchName");
                                if (instBranchName1 ==null || instBranchName1.isEmpty()){
                                    logger.error("{error:\"获取付款单ys银行网点编码失败-资金调拨审批单"+businessId+"中银行网点名称不存在！！！\"}");
                                    //throw new RuntimeException("{error:\"获取付款单ys银行网点编码失败-资金调拨审批单"+businessId+"中银行网点名称不存在！！！\"}");
                                }else {
                                    JSONObject instBranchName = ysDataGetService.getBankDotList(instBranchName1);
                                    if ("200".equals(instBranchName.getStr("code"))){
                                        JSONArray jsonArray1 = instBranchName.getJSONObject("data").getJSONArray("recordList");
                                        if (!jsonArray1.isEmpty()){
                                            fundPaymentBItem.put("oppositebankaddr",jsonArray1.getJSONObject(0).getStr("id")); //收款方开户行名称
                                            fundPaymentBItem.put("oppositebanklineno",jsonArray1.getJSONObject(0).getStr("linenumber")); //收款方银行联行号
                                            fundPaymentBItem.put("oppositebankType",jsonArray1.getJSONObject(0).getStr("bank")); //收款方银行类别

                                            bankParamMap.put("openaccountbank",jsonArray1.getJSONObject(0).getStr("id")); //银行网点id
                                            bankParamMap.put("bank",jsonArray1.getJSONObject(0).getStr("bank")); //银行类型id
                                        }else{
                                            throw new RuntimeException("{error:\"获取付款单ys银行网点编码失败-资金调拨审批单"+businessId+"中银行网点编码不存在！！！\"}");
                                        }
                                    }
                                }
                                if("vendor".equals(caobject)) {
                                    //获取供应商编码
                                    String vendorCode = defaultDataService.getVendorCode(extValueJson.getStr("name"), bankParamMap, vendorList);
                                    if (vendorCode == null){
                                        throw new RuntimeException("{error:\"获取供应商编码失败-预付款审批单"+businessId+"中供应商编码不存在！！！\"}");
                                    }
                                    fundPaymentBItem.put("oppositeobjectname", vendorCode); // 付款对象(供应商)
                                    logger.info("供应商编码{}",vendorCode);
                                }else if ("staff".equals(caobject)) {
                                    JSONArray jsonArrayExtValue = jsonArray.get(1).getJSONArray("extValue");
                                    //获取员工id
                                    if (!jsonArrayExtValue.isEmpty()){
                                        String staffId = jsonArrayExtValue.getJSONObject(0).getStr("emplId");
                                        fundPaymentBItem.put("oppositeobjectname", staffId); // 付款对象(员工)
                                        //fundPaymentBItem.put("oppositeaccountname",jsonArray.getJSONObject(1).getStr("value"));//收款方账户名称。
                                    }
                                }
                                //logger.info("转入银行账号:{}",cardNo);

                            }else if ("ALIPAY_ACCOUNT".equals(identityType)){
                                //结算方式为支付宝支付-无需设置账号
                                paramMap.put("settlemode_code",defaultDataService.SETTLEMODE_CODE[1]);
                                fundPaymentBItem.put("settlemode_code",defaultDataService.SETTLEMODE_CODE[1]); //子表结算方式
                            }
                            break;
                        }
                    }
                }
                processInstance.setUpdateDate(new Date());
                processInstance.setBusinessId(businessId);
                //发送请求保存到ys中
                if ("fundCollection".equals(saveType)) {
                    //保存到资金收款单中
                    fundPaymentBList.add(fundPaymentBItem);
                    paramMap.put("FundCollection_b", fundPaymentBList); //将子表放入到主表中
                    dataMap.put("data", paramMap); //最终封装的数据
                    logger.info(JSONUtil.toJsonStr(dataMap));
                    jsonObjectResponse = defaultDataService.sendPostToSaveFundCollection(dataMap);
                    if (jsonObjectResponse.getStr("code").equals("200")){
                        //保存成功，数据库中修改标记
                        JSONObject data = jsonObjectResponse.getJSONObject("data");
                        String id = data.getStr("id");
                        Map<String,Object> submit=new HashMap<>();
                        Map<String,Object> submitdata=new HashMap<>();
                        submitdata.put("id",id);
                        submit.put("data",submitdata);
                        jsonObjectResponse = defaultDataService.sendPostToSubmit(submit); //发送请求

                    }
//                    处理响应结果
                    defaultDataService.processResponseResults(jsonObjectResponse,businessId,saveType,processInstance);
                }else {
                    //保存到资金付款单中
                    fundPaymentBList.add(fundPaymentBItem);
                    paramMap.put("FundPayment_b", fundPaymentBList); //将子表放入到主表中
                    dataMap.put("data", paramMap); //最终封装的数据
                    logger.info(JSONUtil.toJsonStr(dataMap));
                    jsonObjectResponse = defaultDataService.sendPostToSaveFundPayment(dataMap);
//                    //处理响应结果
                    defaultDataService.processResponseResults(jsonObjectResponse,businessId,saveType,processInstance);
                }
//                ysJsonResponseList.add(jsonObjectResponse);
                ysJsonResponseList.add(new JSONObject(dataMap));
            }catch (Exception e){
                //回显错误信息
                ysJsonResponseList.add(new JSONObject(e.getMessage()));
                //e.printStackTrace();
                //记录xxl-job日志
                defaultDataService.InsertLogger(businessId,"0",e.getMessage(),"panzhinew2");
                logger.error("错误信息:{}", e.getMessage());
                logger.info("----------------------------------------------------------------------------------------------");
            }
        }
        return ysJsonResponseList;
    }

    @Override
    public List<JSONObject> newadvancePayment_toYsJson(List<JSONObject> jsonObjectList) {
//        List<JSONObject> filterReviewer = defaultDataService.filter_Reviewer(jsonObjectList);
        List<JSONObject> ysJsonResponseList = new ArrayList<>(); //返回结果列表
        Map<String, Object> dataMap = null; //参数汇总
        //保存收付款类型
        String saveType = "";
        //保存付款对象标识
        String caobject;
        //获取单据号(显示错误信息)
        String businessId = "";
        //获取响应结果
        JSONObject jsonObjectResponse;
        //获取银行数据
        List<JSONObject> bankList = ysDataGetService.getBankDetailsMessage();
        //获取供应商列表
        List<JSONObject> vendorList = ysDataGetService.getVendorDetailsMessage();

        //遍历ID集合构建参数
        for (JSONObject jsonObject : jsonObjectList) {
            try {
                //保存付款对象标识
                caobject = "";
                //获取审批实例业务编号
                businessId = jsonObject.getJSONObject("result").getStr("businessId");
                JSONArray jsonArrayTasks = jsonObject.getJSONObject("result").getJSONArray("tasks");
                //审批id对象
                ProcessInstance processInstance = defaultDataService.getProcessInstance(jsonArrayTasks);
                Date dateTime = processInstance.getCreateDate();
                String processInstanceId =processInstance.getProcessInstanceId();
                dataMap = new HashMap<>();
                //构建主表参数
                Map <String,Object> paramMap = new HashMap<>();
                paramMap.put("vouchdate",dealTime(jsonObject.getJSONObject("result").getStr("createTime"))); //日期
                paramMap.put("exchangeRateType_code",defaultDataService.EXCHANGE_RATE_TYPE_CODE); //交易类型
                paramMap.put("description",businessId); //审批单据号
                paramMap.put("code",businessId); //审批单据号
                paramMap.put("exchRate",defaultDataService.EXCH_RAGE); //汇率
                paramMap.put("currency_code",defaultDataService.CURRENCY_CODE); //币种code
                paramMap.put("_status","Insert"); //动作

                //构建资金付款单子表参数
                List<Map<String, Object>> fundPaymentBList = new ArrayList<>();
                Map<String, Object> fundPaymentBItem = new HashMap<>();
                fundPaymentBItem.put("settlestatus", "1"); // 结算方式
                fundPaymentBItem.put("_status", "Insert"); // 动作


                //设置单据创建时间
                processInstance.setCreate(jsonObject.getJSONObject("result").getStr("create"));

                List<JSONObject> jsonArray = jsonObject.getJSONObject("result").getJSONArray("formComponentValues").toList(JSONObject.class);
                List<JSONObject> sqrList = jsonArray.stream()
                        .filter(json -> "InnerContactField_1GMI3E9XP4RK0".equals(json.getStr("id")))
                        .collect(Collectors.toList());
                if(sqrList.size()>0){
                    JSONObject sqr = sqrList.get(0);
                    List<JSONObject> extValue = sqr.getJSONArray("extValue").toList(JSONObject.class);
                    if(extValue.size()>0){
                        fundPaymentBItem.put("operator_code", extValue.get(0).getStr("emplId")); // 动作
                    }
                }
                //遍历组件里的value值
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject item = jsonArray.get(i);
                    //设置金额
                    if ("MoneyField-JPATT8BR".equals(item.getStr("id"))){
                        double oriSum = Double.parseDouble(item.getStr("value"));
                        if (oriSum < 0){
                            saveType = "fundCollection";
                            paramMap.put("tradetype_code", defaultDataService.TRADE_TYPE_CODE[3]); //交易类型(其他付款)
                            fundPaymentBItem.put("oriSum", Math.abs(oriSum)); //转为正数
                        }else {
                            saveType = "fundPayment";
                            paramMap.put("tradetype_code", defaultDataService.TRADE_TYPE_CODE[1]); //交易类型(采购付款)
                            fundPaymentBItem.put("oriSum", oriSum);
                        }
                        continue;
                    }
                    //设置部门编码
                    if ("TableField-MINGXI".equals(item.getStr("id"))){
                        JSONArray value = item.getJSONArray("value");
                        JSONArray rowValue = value.getJSONObject(0).getJSONArray("rowValue");
                        //检查该数据中是否包含extendValue
                        if (rowValue.getJSONObject(0).containsKey("extendValue")){
                            JSONArray extendValue = rowValue.getJSONObject(0).getJSONArray("extendValue");
                            String dept_code = extendValue.getJSONObject(0).getStr("id");
                            paramMap.put("dept_code",dept_code);
                            //System.out.println("部门编码:"+dept_code);
                        }
                        continue;
                    }
                    //设置款项类型
                    if ("DDSelectField_1D8BICWKWD5S0".equals(item.getStr("id"))){
                        String type = item.getStr("value");
                        if ("预付款".equals(type)){
                            fundPaymentBItem.put("quickType_code", defaultDataService.QUICK_TYPE_CODE[1]); // 款项类型(预付款)
                            //根据款项类型设置付款对象
                            fundPaymentBItem.put("caobject", 2); // 付款对象(供应商)
                            caobject = "vendor"; //供应商

                        }else if(type.contains("收押金")){
                            fundPaymentBItem.put("quickType_code", defaultDataService.QUICK_TYPE_CODE[6]); //款项类型(押金)
                            //根据款项类型设置付款对象
                            fundPaymentBItem.put("caobject", 2); // 付款对象(供应商)
                            caobject = "vendor"; //供应商

                        }else if ("备用金".equals(type)){
                            fundPaymentBItem.put("quickType_code", defaultDataService.QUICK_TYPE_CODE[5]); //款项类型(备用金)
                            fundPaymentBItem.put("caobject", 4); // 收款对象(其他)
                            caobject = "other"; //其他

                        }else if("借款".equals(type)){
                            fundPaymentBItem.put("quickType_code", defaultDataService.QUICK_TYPE_CODE[4]); //款项类型(借款)
                            fundPaymentBItem.put("caobject", 4); // 收款对象(其他)

                        }else if(type.contains("付押金")){
                            fundPaymentBItem.put("quickType_code", defaultDataService.QUICK_TYPE_CODE[3]); //款项类型(借款)
                            fundPaymentBItem.put("caobject", 2); // 收款对象(供应商)
                            caobject = "vendor"; //供应商
                        }else {
                            throw new RuntimeException("{error:\"获取企业银行账号失败-预付款审批单"+businessId+"中款项类型不存在！！！\"}");
                        }
                        continue;
                    }
                    //设置主体(组织单元)
                    if ("DDSelectField_1B6NZ0TBQOW00".equals(item.getStr("id"))){
                        //付款主体为其他主体直接跳出本次循环
                        if ("其他主体".equals(item.getStr("value"))){
                            continue;
                        }
                        //缓存到redis中
                        String uitCodeKey = "组织名称:" + item.getStr("value");
                        String uitCode = (String) RedisUtils.get(uitCodeKey);
                        //不存在发送请求获取组织编码
                        if (StringUtils.isEmpty(uitCode)){
                            //根据组织名称获取code
                            uitCode = ysDataGetService.getOrgUitCode(item.getStr("value"));
                            RedisUtils.set(uitCodeKey, uitCode);
                        }
                        if (uitCode!=null && !uitCode.isEmpty()){
                            paramMap.put("accentityRaw_code",uitCode ); //会计主体code
                            paramMap.put("accentity_code", uitCode); //资金组织code
                            paramMap.put("org_code", uitCode); //业务组织code
                            String bankCode = defaultDataService.getBankCode(item.getStr("value"),bankList);
                            if (bankCode!=null && !bankCode.isEmpty()){
                                paramMap.put("enterprisebankaccount_code",bankCode);// 企业银行账户编码
                                fundPaymentBItem.put("enterprisebankaccount_code", bankCode); // (子表)企业银行账户编码
                            }else {
                                throw new RuntimeException("{error:\"获取企业银行账号失败-预付款审批单"+businessId+"中默认银行账号不存在！！！\"}");
                            }
                        }else {
                            throw new RuntimeException("{error:\"获取组织code失败-预付款审批单"+businessId+"中组织单元不存在！！！\"}");
                        }
                        continue;
                    }
                    //付款主体为其他主体
                    if("DDSelectField_4EFG20QMDPC0".equals(item.getStr("id"))){
                        if (item.containsKey("extValue")){
                            //缓存到redis中
                            String uitCodeKey = "组织名称:" + item.getStr("value");
                            String uitCode = (String) RedisUtils.get(uitCodeKey);
                            //不存在发送请求获取组织编码
                            if (StringUtils.isEmpty(uitCode)){
                                //根据组织名称获取code
                                uitCode = ysDataGetService.getOrgUitCode(item.getStr("value"));
                                RedisUtils.set(uitCodeKey, uitCode);
                            }
                            if (uitCode!=null && !uitCode.isEmpty()){
                                paramMap.put("accentityRaw_code",uitCode ); //会计主体code
                                paramMap.put("accentity_code", uitCode); //资金组织code
                                paramMap.put("org_code", uitCode); //业务组织code
                                String bankCode = defaultDataService.getBankCode(item.getStr("value"),bankList);
                                if (bankCode!=null && !bankCode.isEmpty()){
                                    paramMap.put("enterprisebankaccount_code",bankCode);// 企业银行账户编码
                                    fundPaymentBItem.put("enterprisebankaccount_code", bankCode); // (子表)企业银行账户编码
                                }else {
                                    throw new RuntimeException("{error:\"获取企业银行账号失败-预付款审批单"+businessId+"中默认银行账号不存在！！！\"}");
                                }
                            }else {
                                throw new RuntimeException("{error:\"获取组织code失败-预付款审批单"+businessId+"中组织单元不存在！！！\"}");
                            }
                            continue;
                        }
                    }
                    //设置收款人银行账号和结算方式
                    if ("RecipientAccountField-JVM0OK11".equals(item.getStr("id"))){
                        if (item.containsKey("extValue")){
                            JSONObject extValueJson = item.getJSONObject("extValue");
                            if("vendor".equals(caobject)) {
                                if (!extValueJson.containsKey("cardNo")) {
                                    logger.error("供应商银行账号不存在!");
                                    //throw new RuntimeException("{error:\"获取供应商银行账号失败-预付款审批单" + businessId + "中供应商收款账号不存在！！！\"}");
                                }
                            }
                            String identityType = extValueJson.getStr("identityType");
                            String name = extValueJson.getStr("name");
                            fundPaymentBItem.put("oppositeobjectname", name); // 付款单位
                            fundPaymentBItem.put("oppositeaccountname",name);//收款方账户名称。
                            //结算方式判断
                            if ("CORP_BANK_CARD".equals(identityType) || "PERSONAL_BANK_CARD".equals(identityType)){
                                if (!extValueJson.containsKey("cardNo")) {
                                    throw new RuntimeException("{error:\"获取供应商银行账号失败-预付款审批单" + businessId + "中供应商收款账号不存在！！！\"}");
                                }
                                paramMap.put("settlemode_code",defaultDataService.SETTLEMODE_CODE[0]); //结算方式
                                fundPaymentBItem.put("settlemode_code",defaultDataService.SETTLEMODE_CODE[0]); //子表结算方式
                                String cardNo = extValueJson.getStr("cardNo");
                                fundPaymentBItem.put("oppositeaccountno", cardNo); // 收款(付款)银行账号

                                //供应商子表银行网点信息参数
                                Map<String,Object> bankParamMap = new HashMap<>();
                                bankParamMap.put("account",extValueJson.getStr("cardNo")); //银行账号
                                bankParamMap.put("accountname",extValueJson.getStr("name")); ////账号名称
                                //获取银行网点信息
                                String instBranchName1 = extValueJson.getStr("instBranchName");
                                if (instBranchName1 ==null || instBranchName1.isEmpty()){
                                    logger.error("{error:\"获取付款单ys银行网点编码失败-资金调拨审批单"+businessId+"中银行网点名称不存在！！！\"}");
                                    //throw new RuntimeException("{error:\"获取付款单ys银行网点编码失败-资金调拨审批单"+businessId+"中银行网点名称不存在！！！\"}");
                                }else {
                                    JSONObject instBranchName = ysDataGetService.getBankDotList(instBranchName1);
                                    if ("200".equals(instBranchName.getStr("code"))){
                                        JSONArray jsonArray1 = instBranchName.getJSONObject("data").getJSONArray("recordList");
                                        if (!jsonArray1.isEmpty()){
                                            fundPaymentBItem.put("oppositebankaddr",jsonArray1.getJSONObject(0).getStr("id")); //收款方开户行名称
                                            fundPaymentBItem.put("oppositebanklineno",jsonArray1.getJSONObject(0).getStr("linenumber")); //收款方银行联行号
                                            fundPaymentBItem.put("oppositebankType",jsonArray1.getJSONObject(0).getStr("bank")); //收款方银行类别

                                            bankParamMap.put("openaccountbank",jsonArray1.getJSONObject(0).getStr("id")); //银行网点id
                                            bankParamMap.put("bank",jsonArray1.getJSONObject(0).getStr("bank")); //银行类型id
                                        }else{
                                            throw new RuntimeException("{error:\"获取付款单ys银行网点编码失败-资金调拨审批单"+businessId+"中银行网点编码不存在！！！\"}");
                                        }
                                    }
                                }
                                if("vendor".equals(caobject)) {
                                    //获取供应商编码
                                    String vendorCode = defaultDataService.getVendorCode(extValueJson.getStr("name"), bankParamMap, vendorList);
                                    if (vendorCode == null){
                                        throw new RuntimeException("{error:\"获取供应商编码失败-预付款审批单"+businessId+"中供应商编码不存在！！！\"}");
                                    }
                                    fundPaymentBItem.put("oppositeobjectname", vendorCode); // 付款对象(供应商)
                                    logger.info("供应商编码{}",vendorCode);
                                }else if ("staff".equals(caobject)) {
                                    JSONArray jsonArrayExtValue = jsonArray.get(1).getJSONArray("extValue");
                                    //获取员工id
                                    if (!jsonArrayExtValue.isEmpty()){
                                        String staffId = jsonArrayExtValue.getJSONObject(0).getStr("emplId");
                                        fundPaymentBItem.put("oppositeobjectname", staffId); // 付款对象(员工)
                                        //fundPaymentBItem.put("oppositeaccountname",jsonArray.getJSONObject(1).getStr("value"));//收款方账户名称。
                                    }
                                }
                                //logger.info("转入银行账号:{}",cardNo);

                            }else if ("ALIPAY_ACCOUNT".equals(identityType)){
                                //结算方式为支付宝支付-无需设置账号
                                paramMap.put("settlemode_code",defaultDataService.SETTLEMODE_CODE[1]);
                                fundPaymentBItem.put("settlemode_code",defaultDataService.SETTLEMODE_CODE[1]); //子表结算方式
                            }
                            break;
                        }
                    }
                }
                processInstance.setUpdateDate(new Date());
                processInstance.setBusinessId(businessId);
                //发送请求保存到ys中
                if ("fundCollection".equals(saveType)) {
                    //保存到资金收款单中
                    fundPaymentBList.add(fundPaymentBItem);
                    paramMap.put("FundCollection_b", fundPaymentBList); //将子表放入到主表中
                    dataMap.put("data", paramMap); //最终封装的数据
                    logger.info(JSONUtil.toJsonStr(dataMap));
                    jsonObjectResponse = defaultDataService.sendPostToSaveFundCollection(dataMap);
                    if (jsonObjectResponse.getStr("code").equals("200")){
                        //保存成功，数据库中修改标记
                        JSONObject data = jsonObjectResponse.getJSONObject("data");
                        String id = data.getStr("id");
                        Map<String,Object> submit=new HashMap<>();
                        Map<String,Object> submitdata=new HashMap<>();
                        submitdata.put("id",id);
                        submit.put("data",submitdata);
                        jsonObjectResponse = defaultDataService.sendPostToSubmit(submit); //发送请求

                    }
//                    处理响应结果
                    defaultDataService.processResponseResults(jsonObjectResponse,businessId,saveType,processInstance);
                }else {
                    //保存到资金付款单中
                    fundPaymentBList.add(fundPaymentBItem);
                    paramMap.put("FundPayment_b", fundPaymentBList); //将子表放入到主表中
                    dataMap.put("data", paramMap); //最终封装的数据
                    logger.info(JSONUtil.toJsonStr(dataMap));
                    jsonObjectResponse = defaultDataService.sendPostToSaveFundPayment(dataMap);
//                    //处理响应结果
                    defaultDataService.processResponseResults(jsonObjectResponse,businessId,saveType,processInstance);
                }
//                ysJsonResponseList.add(jsonObjectResponse);
                ysJsonResponseList.add(new JSONObject(dataMap));
            }catch (Exception e){
                //回显错误信息
                ysJsonResponseList.add(new JSONObject(e.getMessage()));
                //e.printStackTrace();
                //记录xxl-job日志
                defaultDataService.InsertLogger(businessId,"0",e.getMessage(),"panzhi2");
                logger.error("错误信息:{}", e.getMessage());
                logger.info("----------------------------------------------------------------------------------------------");
            }
        }
        return ysJsonResponseList;
    }

    public static String dealTime(String oldTime){

        OffsetDateTime offsetDateTime = OffsetDateTime.parse(oldTime);
        // 定义目标格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化为指定格式
        String formattedTime = offsetDateTime.format(formatter);

        return formattedTime;
    }

}
